// sku.js
var regexp = require('../../utils/regexpUtil.js');
var cart = require('../../utils/cart.js');
var util = require('../../utils/util.js');
var pintuanapi = require('../../component/service/pintuanapi.js');
var countDownT = require('../../component/countDown/countDownT.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    skuId: '',
    hidden: false,
    sku: {},
    desc:'',
    showSection:'desc',
    quantity: 1,
    skuPrices:[],
    images:[],
    isShared:false,
    comment:{
      total:{
        commentVal:100,
        commentVal1:100,
        commentVal2:100,
        commentVal3:100,
        commentVal4:100,
        commentVal5:100,
      }
    },//评价详情
    sales:[],//最近成交列表
    totalPrice:0,
    pintuan:null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    if(typeof(options.isShared)!='undefined')
      this.data.isShared = options.isShared;
    that.setData({
      skuId: options.skuId,
      isShared:this.data.isShared
    }),
    wx.request({
    url: getApp().globalData.host + '/webapp/resource/getSku.html?skuId=' + this.data.skuId,
    header: getApp().globalData.header,
      success: function (res) {
        if(typeof(res.data)!='undefined'&&res.data.skuId!=''){
          //that.addImages(res.data);
          if(typeof(res.data.summary)!='undefined'&&res.data.summary.indexOf('买一送一')>-1){
            res.data.promotion = true;
          }
          that.setData({
            sku: res.data,
            quantity:res.data.wholesaleMinQuantity,
            hidden:true
          });
        }
      },
      complete:function(res){
        that.skuPrices();
      }
    })
    this.getSkuDesc();
    this.skuImages();
    this.skuComments();
    this.skuSales();
    pintuanapi.skuAndPintuan(this.data.skuId,function(res){
      let countDown = new countDownT();
      countDown.setExpireTime(res.serverTime,res.expireTime,"pintuan.countDownT",that,res.validTime);
      res.countDownT = countDown;
      that.setData({
        pintuan:res
      });
    });
  },
  pintuanDetail:function(){
    wx.navigateTo({
      url: '../pintuan/pintuan?itemId=' + this.data.pintuan.itemId,
    })
  },
  getSkuDesc:function(){
    var that = this;
    wx.request({
      url: getApp().globalData.host + '/webapp/resource/skuDesc.html?skuId=' + this.data.skuId,
      header: getApp().globalData.header,
      success: function (res) {
        that.setData({
          desc: getApp().globalData.imgHost + regexp.regexpImg(res.data.desc)
        });    
      }
    })
  },
  skuPrices:function(){
    var that = this;
    wx.request({
      url: getApp().globalData.host + 'webapp/resource/skuPrices.html?skuId=' + this.data.skuId,
      header: getApp().globalData.header,
      success: function (res) {
        if(res.data.length>0&&typeof(res.data[0].priceId)!='undefined')
          that.data.skuPrices = res.data;
        else{
          var skuPrice = {price:that.data.sku.price,minQuantity:that.data.sku.wholesaleMinQuantity,selected:true};
          that.data.skuPrices.push(skuPrice);
        }
        that.setData({
          skuPrices: that.data.skuPrices
        });    
        that.effectPrice();
      }
    })
  },
  selectPrice:function(e){
    var index = e.currentTarget.dataset.index;
    this.setData({
      quantity:this.data.skuPrices[index].minQuantity
    })
    this.effectPrice();
  },
  skuImages:function(){
    var that = this;
    wx.request({
      url: getApp().globalData.host + '/webapp/resource/skuImages.html?skuId=' + that.data.skuId,
      header: getApp().globalData.header,
      success: function (res) {
        if(typeof(res.data)!='undefined'&&res.data.length>0){
          that.setData({
            images:res.data
          });
          //that.addImages(res.data);
        }
      }
    })
  },
  previewImg:function(e){
    var imgUrl = e.currentTarget.dataset.imgUrl;
    if (typeof (imgUrl) != 'undefined' && imgUrl.length>0) {
      let urls = [];
      urls.push(imgUrl);
      wx.previewImage({
        urls: urls
      })
    }
  },
  addImages:function(imgs){
    if(imgs instanceof Array){
      for(var i = 0;i<imgs.length;i++){
        var isExist  = false;
        for(var j = 0;j<this.data.images.length;j++){
          if(this.data.images[j]==imgs[i].url){
            isExist = true;
            break;
          }
        }
        if(!isExist){
          this.data.images.push(imgs[i].url);
        }
      }
    }else{
      var isExist  = false;
      for(var j = 0;j<this.data.images.length;j++){
        if(this.data.images[j]==imgs.imgUrl){
          isExist = true;
          break;
        }
      }
      if(!isExist){
        this.data.images.push(imgs.imgUrl);
      }
    }    
    this.setData({
      images:this.data.images
    });
  },
  //获取商品评价列表
  skuComments:function(){
    let that = this;
    wx.request({
      url: getApp().globalData.host + 'sku/commentsForDetail',
      data: { skuId: that.data.skuId, pageIndex:0},
      header: getApp().globalData.header,
      method: 'POST',
      success: function (res) {
        if(typeof(res.data.comments)!="undefined"&&res.data.comments.records.length>0){
          let comments = res.data.comments.records;
          for(let i = 0;i < comments.length;i++){
            comments[i].createTime = util.formatTimeStamp(comments[i].createTime);
            if(typeof(comments[i].imgUrls)!="undefined"){
              for(let j = 0;j < comments[i].imgUrls.length;j++){
                comments[i].imgUrls[j] = getApp().globalData.imgHost + comments[i].imgUrls[j];
              }
            }
          }
          that.setData({
            comment: res.data
          });
        }
        if(typeof(res.data.total)!="undefined"&&res.data.total.skuId.length>0){
          that.setData({
            comment: res.data
          });
        }        
      },
      fail: function (res) {},
      complete: function (res) {}
    })
  },
  //浏览评价详情图片
  commentImages:function(e){
    let index = e.target.dataset.index;
    let currentUrl = e.target.dataset.current;
    let that = this;
    wx.previewImage({
      current: currentUrl, 
      urls: that.data.comment.comments.records[index].imgUrls
    })
  },
  //获取商品成交列表
  skuSales:function(){
    let that = this;
    wx.request({
      url: getApp().globalData.host + 'sku/salesListForDetail',
      data: { skuId: that.data.skuId, pageIndex:0},
      header: getApp().globalData.header,
      method: 'POST',
      success: function (res) {
        let rsales = res.data.records
        if(typeof(rsales)!="undefined"){
          for(let i = 0;i<rsales.length;i++){
            rsales[i].payTime = util.formatTimeStamp(rsales[i].payTime);
          }
          that.setData({
            sales: rsales
          });
        }
      },
      fail: function (res) {},
      complete: function (res) {}
    })
  },
  changeSection:function(e){
    this.setData({
      showSection:e.target.dataset.name
    })
  },
  reduce: function(){
    if(this.data.quantity<this.data.sku.wholesaleMinQuantity) return;
    this.modifyQuantity(-1);
  },
  add: function(){
    this.modifyQuantity(1);
  },
  modifyQuantity:function(num){
    var quantity = this.data.quantity+num;
    if(quantity>this.data.sku.actualWholesaleMaxQuantity) quantity=this.data.sku.actualWholesaleMaxQuantity;
    if(quantity<this.data.sku.wholesaleMinQuantity) quantity=this.data.sku.wholesaleMinQuantity;
    this.setData({
      quantity: quantity
    });
    this.effectPrice();
  },
  quantityChange:function(e){
    var reg = /^[1-9]+[0-9]*]*$/; //判断正整数
    var changetQty = e.detail.value;
    if(reg.test(changetQty)){
      changetQty = parseInt(changetQty);
      if(changetQty<this.data.sku.wholesaleMinQuantity) changetQty=this.data.sku.wholesaleMinQuantity;
      if(changetQty>this.data.sku.actualWholesaleMaxQuantity) changetQty=this.data.sku.actualWholesaleMaxQuantity;
      this.setData({
        quantity: changetQty
      });
      this.effectPrice();
    }else{
      this.setData({
        quantity: this.data.quantity
      });
    }
  },
  //设置有效价格 后台列表按minQuantity升序，所以最后一个符合要求的价格为生效价格
  effectPrice:function(){
    var index = null;
    for(var i = 0;i<this.data.skuPrices.length;i++){
      if(this.data.quantity>=this.data.skuPrices[i].minQuantity)
        index = i;
      this.data.skuPrices[i].selected = false;
    }
    if(null!=index){
      this.data.skuPrices[index].selected = true;
      this.data.totalPrice = this.data.skuPrices[index].price*this.data.quantity;
    }
    this.setData({
      skuPrices: this.data.skuPrices,
      totalPrice:this.data.totalPrice
    });
  },
  addShoppingCart: function(e){
    cart.add(this.data.sku,this.data.quantity,true);
  },
  buyNow:function(e){
    var that = this;
    if (getApp().globalData.platUser == null) {//用户未登录 跳转至登录页面
      wx.navigateTo({
        url: '../login/login'
      });
    }else{
      wx.request({
        url: getApp().globalData.host + 'webapp/orders/confirm.html',
        data: {skuId: that.data.skuId, quantity:that.data.quantity},
        header: getApp().globalData.header,
        success: function (res) {
          if (typeof (res.data) != 'undefined' && typeof (res.data.orderId) != 'undefined')
            wx.navigateTo({
              url: '../confirm/confirm?orderId=' + res.data.orderId
            });
          else {
            wx.showModal({
              title: '创建订单失败',
              content: res.data,
              showCancel: false
            })
          }
        }
     })
    }
  },
  //分享该页面
  onShareAppMessage: function () {
    return {
      title: '[分享] ' + this.data.sku.skuName,
      path: '/pages/sku/sku?skuId=' + this.data.skuId
    }
  },
  //返回首页
  goHome:function(){
    wx.switchTab({
      url: '/pages/index/index'
    })
  },
  //跳转购物车
  shoppingcart:function(){
    wx.switchTab({
      url: '/pages/shoppingCart/shoppingCart'
    })
  },
  //拨打客服电话
  contactService:function(){
    wx.makePhoneCall({
      phoneNumber: getApp().globalData.servicePhone
    })
  },
  //购买品鉴装
  //将来需要考虑跳转超过5层的问题
  buySample:function(){
    wx.navigateTo({
      url: '../sample/sample?sku=' + JSON.stringify(this.data.sku),
    })
  }
})